/**
 * Created by oneminute on 8/30/14.
 *
 * 通过消息队列接收日志消息并在命令行显示,且将其插入数据库中.
 */

var amqp = require("amqp");
var config = require("../../config/config");
var moment = require("moment");
var common = require("winston/lib/winston/common");

exports.run = function () {
    console.log(moment().format(config.datetimeFormatLong) + " - info: [iwant " + process.pid + "] 日志应用角色启动.");

    var connection = amqp.createConnection(config.rabbit.server);

    connection.on("error", function (_err) {
        console.error(_err);
    });

    connection.on("ready", function () {
        console.log("[client] connection is ready.");
        connection.queue("", {
            durable: true,
            autoDelete: true
        }, function (_queue) {
            console.log("[client] queue " + _queue.name + " is openned.");
            _queue.bind(config.rabbit.log.exchange, "iwant.#");
            _queue.on("queueBindOk", function () {
                console.log("[client] queue bind ok.");

                _queue.subscribe({}, function (_msg) {
                    _msg.prettyPrint = true;
                    _msg.colorize = true;
                    var timestamp = _msg.timestamp;
                    _msg.timestamp = function () {
                        return timestamp;
                    };
                    var output = common.log(_msg);
                    if (_msg.level === 'error' || _msg.level === 'debug') {
                        process.stderr.write(output + '\n');
                    } else {
                        process.stdout.write(output + '\n');
                    }
                });
            });
        });
    });
};
